package com.tnl.web.taglib;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.tnl.web.dao.AdminUserDAO;
import com.tnl.web.dao.PermissionDAO;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.domain.Permission;

public class AccessorTags {
	private static Logger logger = LoggerFactory.getLogger(AccessorTags.class);

	public static boolean hasPermission(String userId, String permission) {
		// getApplicationcontext
		// get authorize bean
		// get user and user ROle
		// permission

		PermissionDAO permDAO = ApplicationContextHolder.getBean(
				"permissionDAO", PermissionDAO.class);

		AdminUserDAO userDAO = ApplicationContextHolder.getBean("adminUserDAO",
				AdminUserDAO.class);
		if (StringUtils.hasText(userId)) {
			Integer id = Integer.valueOf(userId);
			AdminUser user = userDAO.findByID(id);
			if (user == null) {
				
				logger.error("can not find the user(id =" +id+ ")");
				return false;
			}
			List<Permission> permissions = permDAO.getRolesPermission(user
					.getRoleId());

			for (Permission perm : permissions) {
				if (perm.getPermissionName().equals(permission)) {
					return true;
				}
			}
		}

		return false;
	}

}
